<?php

declare(strict_types=1);

namespace app\backend\controller\sys;

use app\common\controller\Basic;
use app\common\service\sys\FolderTypeService;

/**
 * 我的文件夹 控制器
 * @author kaige
 * @update  2023-09-01
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class FolderType extends Basic
{

  // 初始化
  protected function initialize()
  {
    parent::initialize();
    // 当前控制器服务实例化
    $this->service = new FolderTypeService();
  }

  /**
   * 列表 -- Layui treeTable 特殊树型
   * 只取个人的
   */
  public function index()
  {
    if ($this->request->isGet()) {
      $data = input('param.');
      $data['user_id'] = $this->user['id'];
      $result = $this->service->_list($data, false);
      $tree = [];
      if ($result && $result['count'] > 0) {
        $tree = \app\common\util\TreeUtil::list_to_tree($result['data'], 0, 'id', 'pid', 'children');
        \app\common\util\TreeUtil::tree_add_field($tree);
      }
      return json(_layui($result['count'], $tree));
    }
    return _jerr(1000);
  }

  /**
   * 添加
   */
  public function add()
  {
    if ($this->request->isPost()) {
      $data = input('param.');
      $data['user_id'] = $this->user['id'];
      $this->_form_filter($data);
      return json($this->service->saveForm($data));
    }
    if ($this->request->isGet()) {
      $data = [];
      return _jok('ok', $data);
    }
    return _jerr(1000);
  }

  /**
   * 编辑
   */
  public function edit()
  {
    $id = input('id/d', 0);
    if ($id === 0) {
      return _jerr(1022);
    }
    if ($this->request->isPost()) {
      $data = input('param.');
      if ($data['user_id'] != $this->user['id']) {
        return _jerr('不能编辑他人的');
      }
      $this->_form_filter($data);
      return json($this->service->saveForm($data));
    }
    if ($this->request->isGet()) {
      $data = $this->service->getInfoById($id);
      return _jok('ok', $data);
    }
    return _jerr(1000);
  }

  /**
   * 添加编辑-表单数据处理
   */
  protected function _form_filter(&$data)
  {
    url_decode($data);
  }

  /**
   * 删除
   */
  public function del()
  {
    if ($this->request->isPost()) {
      $id = input('id/d', 0);
      if($id == 1){
        return _jerr('删除失败，不允许操作');
      }
      $list = $this->service->getListAll([
        ['pid', '=', $id]
      ]);
      if ($list) {
        return _jerr('删除失败，存在子项');
      } else {
        if ($this->service->delete($id)) {
          return _jok(1025);
        };
      }
      return _jerr(1026);
    }
    return _jerr(1000);
  }
}
